/* include ---------------------------------------------------------*/
#include "flash_dev.h"


/* private define -------------------------------------------------*/


/* private variables ----------------------------------------------*/
uint32_t lock = 3;

/* private function prototypes ------------------------------------*/


/* public variables -----------------------------------------------*/


/**
  * @brief  获取上锁次数
  * @param  None
  * @retval 返回内存记录的次数
  * @note   None
*/
static uint32_t Flash_Get_Lock(void)
{
  uint32_t num = 0xFFFF;
  nvs_handle_t nvs_config;
  esp_err_t err = nvs_open("storage", NVS_READONLY, &nvs_config);
  if(err != ESP_OK)
  {
    printf("Opening NVS error!\n");
  }
  else
  {
    
  }

  if((nvs_get_u32(nvs_config,"lock",&num)) == ESP_OK)
  {
      printf("Read lock num = %d\n",num);
  }
  nvs_close(nvs_config);
  return num;
}


/**
  * @brief  设置上锁次数
  * @param  lock: 次数
  * @retval None
  * @note   None
*/
static void Flash_Write_Lock(uint32_t lock)
{
    nvs_handle_t nvs_config;
    esp_err_t err = nvs_open("storage", NVS_READWRITE, &nvs_config);
    if(err != ESP_OK)
    {
        printf("Opening NVS error!\n");
    }

    if((nvs_set_u32(nvs_config,"lock",lock)) == ESP_OK)
    {
        printf("Write lock num = %d\n",lock);
    }
    nvs_close(nvs_config);
}
/**
  * @brief  程序运行还是上锁判断
  * @param  None
  * @retval 0: 上锁  !0: 运行
  * @note   None
*/
uint8_t runOrLock(void)
{
    uint32_t lockNum = 0;
    lockNum = Flash_Get_Lock();
    if(lockNum == 0xFFFF)
    {
        vTaskDelay(10 / portTICK_PERIOD_MS);
        Flash_Write_Lock(lock);
        vTaskDelay(10 / portTICK_PERIOD_MS);
        lockNum = Flash_Get_Lock();
        if(lockNum != 0)
        {
          vTaskDelay(10 / portTICK_PERIOD_MS);
          Flash_Write_Lock(--lockNum);
          return 1;
        }
    }
    else
    {
        if(lockNum != 0)
        {
          vTaskDelay(10 / portTICK_PERIOD_MS);
          Flash_Write_Lock(--lockNum);
          return 1;
        }
        else 
        {
          return 0;
        }
    }
    return 0;
}
/**
  * @brief  延时锁任务
  * @param  None
  * @retval None
  * @note   None
*/
static void lock_delay_run_task(void *pvParameters)
{
    uint8_t count = 0;
    while(1) 
    {
        vTaskDelay(10000 / portTICK_PERIOD_MS);
        count++;
        if(count > 24) {
            esp_restart();
        }
    }
}

void create_lock_delay_task(void)
{
  xTaskCreate(lock_delay_run_task, "lock_delay_run_task", 2048, NULL, 10, NULL);
}

/**
  * @brief  NVS初始化
  * @param  None
  * @retval None
  * @note   None
*/
void NVS_Flash_Init(void)
{
    esp_err_t err = nvs_flash_init();
    if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND)
    {
        // NVS partition was truncated and needs to be erased
        // Retry nvs_flash_init
        ESP_ERROR_CHECK(nvs_flash_erase());
        err = nvs_flash_init();
    }
}
